<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted, onUnmounted, ref, nextTick, provide } from 'vue'
import { baseURL } from '@/utils/request'
import io, { Socket } from 'socket.io-client'
import { useUserStore } from '@/stores/modules/user'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { getConsultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { showToast } from 'vant'
let socket: Socket
const store = useUserStore()
const route = useRoute()
// 记录是否第一次加载
const initialMsg = ref(true)
// 记录第一条数据的时间
const time = ref('')
// 声明渲染数组
const list = ref<Message[]>([])
// 获取订单状态数据
const consult = ref<ConsultOrderItem>()
// 获取订单状态数据函数
const getData = async () => {
  // 获取订单状态
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}
// 传信息给后代组件
provide('consult', consult)
// 定义修改评价状态函数
const completeEva = (score: number) => {
  // 找到未评价数据
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
// 暴露给后代组件
provide('completeEva', completeEva)
onMounted(() => {
  // 建立链接，创建 socket.io 实例
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // socket.on('connect', () => {
  //   // 建立连接成功
  //   console.log('连接成功')
  // })
  // socket.on('error', (event) => {
  //   // 错误异常消息
  //   console.log(event)
  // })
  // socket.on('disconnect', () => {
  //   // 已经断开连接
  //   console.log('断开连接')
  // })

  // 获取消息
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 转化数组格式
    const arr: Message[] = []
    data.forEach((item, i) => {
      // 记录第一条数据的时间
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    arr.sort((a, b) => +new Date(a.createTime) - +new Date(b.createTime))
    // 追加到聊天消息列表
    list.value.unshift(...arr)
    // 下拉刷新
    loading.value = false
    if (!data.length) {
      return showToast('没有聊天记录了')
    }
    nextTick(() => {
      if (initialMsg.value) {
        // 第一次进来就把之前的所有消息设置已读
        socket.emit('updateMsgStatus', list.value[list.value.length - 1]?.id)
        // 页面滑动到最底部
        window.scrollTo(0, document.documentElement.scrollHeight)
        initialMsg.value = false
      }
    })
  })
  // 初始化执行获取订单状态
  getData()
  // 服务器通知订单发送改变，重新渲染数据
  socket.on('statusChange', () => {
    getData()
  })
  // 接收发送成功或者医生发来的消息
  socket.on('receiveChatMsg', async (data) => {
    list.value.push(data)
    // 把接收的最新消息设置成已读
    socket.emit('updateMsgStatus', data.id)
    nextTick(() => {
      window.scrollTo(0, document.documentElement.scrollHeight)
    })
  })
})
onUnmounted(() => {
  // 组件销毁断开连接
  socket.close()
})
// 接收来自子组件传来的输入框值
const sendText = (val: string) => {
  // 给服务器发送消息
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: val }
  })
}
// 发送图片
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}
// 下拉刷新
const loading = ref(false)
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status
      :status="consult?.status"
      :countdown="(consult?.countdown) as number"
    ></room-status>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message
        v-for="item in list"
        :key="item.id"
        :item="item"
      ></room-message>
    </van-pull-refresh>
    <room-action
      @sendText="sendText"
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-image="sendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);

  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
